package com.sneakxy.cloudbase.platform.utils.web;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * @author 潜行的青衣
 * @see
 */
public class BeanHelper {

	@FunctionalInterface
	public static interface TrimPloy {
		
		public String trim(String value);
		
	}
	
	public static void trim(Object obj, TrimPloy ploy) {
		Class<?> clazz = obj.getClass();
		List<Field> fields = FieldUtils.getAllFieldsList(clazz);
		Iterator<Field> it = fields.iterator();
		Field field = null;
		String value = null;
		while(it.hasNext()) {
			field = it.next();
			if(field.getType() == String.class) {
				try {
					value = (String) FieldUtils.readField(field, obj, true);
					FieldUtils.writeField(field, obj, ploy.trim(value), true);
				} catch (IllegalAccessException e) {
					//无需处理 
				}
			}
		}
	}
	
	public static void trim(Object obj) {
		trim(obj, StringUtils::trim);
	}
	
	public static void trimToEmpty(Object obj) {
		trim(obj, StringUtils::trimToEmpty);
	}
	
	public static void trimToNull(Object obj) {
		trim(obj, StringUtils::trimToNull);
	}
	
	/**
	 * 纵向数据变横向数据
	 * @param transform 字段转换信息
	 * @param data 纵向数据
	 * @param clazz 横向数据类型
	 * @return 横向数据类
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public static <T> T verticalToHorizontal(Map<String, String> transform, Object data, Class<T> clazz) {
		Object value = null;
		Map<String, Object> newData = new LinkedHashMap<>();
		JSONObject oldData = (JSONObject) JSON.toJSON(data);
		for(Entry<String, String> entry: transform.entrySet()) {
			value = oldData.get(entry.getKey());
			newData.put(entry.getValue(), value);
		}
		return new JSONObject(newData).toJavaObject(clazz);
	}
	
	private BeanHelper() {}
	
}
